#include "Application.h"
#include "CommandLine.h"

#include <Poco/Logger.h>
#include <Poco/FileChannel.h>
#include <Poco/FormattingChannel.h>
#include <Poco/PatternFormatter.h>
#include <Poco/Util/IniFileConfiguration.h>
#include <Poco/SharedPtr.h>
#include <Poco/Path.h>
#include <Poco/File.h>

#include "decode/FrameReceiver.h"

using namespace Poco;
using namespace std;

// simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateFileLogger("logger.txt");

int Application::main(const std::vector<std::string> &args)
{
    // 初始化日志系统
    Path logPath = Path(commandPath()).parent().pushDirectory("logs");
    File(logPath).createDirectories();
    logPath.setFileName("percipient-service.log");
    Channel::Ptr pFileChannel = new FileChannel();
    pFileChannel->setProperty("path", logPath.toString());
    pFileChannel->setProperty("rotation", "daily");
    pFileChannel->setProperty("archive", "timestamp");
    pFileChannel->setProperty("compress", "true");
    pFileChannel->setProperty("purgeAge", "30 days");
    PatternFormatter::Ptr pFormatter = new PatternFormatter("%Y-%m-%dT%H:%M:%S %q [%s] %t");
    FormattingChannel::Ptr pFormattingChannel = new FormattingChannel(pFormatter, pFileChannel);
    Poco::Logger::root().setChannel(pFormattingChannel);

    // 读取配置文件
    Path configPath = Path(commandPath()).parent().setFileName("config.ini");
    Util::IniFileConfiguration::Ptr pConfig = new Util::IniFileConfiguration(configPath.toString());
    InitDeviceCfg();

    // 启动解码器
    pReceiver = new FrameReceiver(pCameraInfo);
    pReceiver->Start();

    // 启动命令行
    // CommandLine *pCommandLine = new CommandLine();

    // 等待程序退出
    waitForTerminationRequest();

    // 销毁解码器
    pReceiver->Stop();
    delete pReceiver;

    // 销毁命令行接口
    // delete pCommandLine;

    return Application::EXIT_OK;
}

void Application::InitDeviceCfg()
{
    Path configPath = Path(commandPath()).parent().setFileName("config.ini");
    Util::IniFileConfiguration::Ptr pConfig = new Util::IniFileConfiguration(configPath.toString());
    pCameraInfo.url = pConfig->getString("camera.url", "");
    pCameraInfo.copyHeight = pConfig->getInt("camera.copyheight", -1);

    std::string format = pConfig->getString("camera.format", "");
    if (format == "rawdata")
        pCameraInfo.eFormat = RawData;
    else if (format == "mpeg1")
        pCameraInfo.eFormat = Mpeg1;
    else if (format == "map")
        pCameraInfo.eFormat = Map;
    else
        pCameraInfo.eFormat = NoneFormat;
}